import 'package:extended_image/extended_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_widget/src/config/assets.dart';
import 'package:flutter_widget/src/config/color_define.dart';
import 'package:flutter_widget/src/config/config.dart';
import 'package:flutter_widget/src/widget/button/custom_button.dart';
import 'package:flutter_widget/src/widget/effect/clip_widget.dart';

const Map<String, String> _header = FWConfig.qnHeader;

enum WebCacheImageScale {
  normal, //不压缩
  mini, //很小图 (w<=140)
  small, //小图 (w<=500)
  middle, //中等大小图（w<=1200）
  big, //大图 (w=2000）
  origin, //原图大小
}

/// 默认图片加载用这个 !!
/// radius 切圆角使用，设置为切四个角
/// placeholderImage 占位图，会优先显示，默认"华夏风物"
/// placeholderWidget 自定义占位控件
/// displayPlaceholder 是否显示占位图，
/// errorImage 加载失败图片
/// scale 可设置加载图片比例大小，默认加载原图
/// retry 是否可以点击重试加载图片，默认false
/// headers 自定义请求header
/// maxBytes 图片压缩限制，默认最大500KB
/// clearMemoryCacheWhenDispose 在Flutter2.0后不一定生效, 因为没法在图片没有完成之前释放掉(#317). 现在只会释放已完成的图片资源.
/// imageCacheName 指定一个 ImageCache 来缓存一些图片
/// gaplessPlayback 新图加载完之前显示旧图
// ignore: non_constant_identifier_names
Widget WebCacheImage({
  required String? imageUrl,
  double? width,
  double? height,
  double radius = 0,
  BoxFit? fit,
  String? placeholderImage,
  Widget? placeholderWidget,
  bool displayPlaceholder = true,
  bool bottomLeft = true,
  bool bottomRight = true,
  String? errorImage,
  WebCacheImageScale scale = WebCacheImageScale.big,
  ExtendedImageMode mode = ExtendedImageMode.none,
  bool retry = false,
  Map<String, String>? headers,
  int? cacheWidth,
  int? cacheHeight,
  int? maxBytes,
  bool clearMemoryCacheWhenDispose = false,
  String? imageCacheName,
  bool? gaplessPlayback,
  VoidCallback? loadFinish,
}) {
  String urlString = _getUrlWithSplit(imageUrl, scale);
  // debugPrint("加载图片地址：$_url");
  Widget childWidget() {
    if (imageUrl?.isNotEmpty == true) {
      var image = ExtendedImage.network(
        urlString,
        fit: fit,
        headers: headers ?? _header,
        width: width,
        height: height,
        cache: true,
        mode: mode,
        maxBytes: maxBytes,
        clearMemoryCacheWhenDispose: clearMemoryCacheWhenDispose,
        cacheWidth: cacheWidth,
        cacheHeight: cacheHeight,
        imageCacheName: imageCacheName,
        gaplessPlayback: gaplessPlayback ?? false,
        loadStateChanged: (ExtendedImageState state) {
          if (state.extendedImageLoadState == LoadState.completed &&
              loadFinish != null) {
            loadFinish();
          }
          return getExtendedImageState(
            state: state,
            errorImage: errorImage,
            placeholderWidget: placeholderWidget,
            placeholderImage: placeholderImage,
            displayPlaceholder: displayPlaceholder,
            retry: retry,
          );
        },
      );
      // if (width != null || height != null) {
      //   return SizedBox(
      //     width: width,
      //     height: height,
      //     child: _image,
      //   );
      // } else {
      return image;
      // }
    } else {
      if (displayPlaceholder == false) {
        return Container();
      }
      return SizedBox(
        width: width,
        height: height,
        child: (errorImage?.isNotEmpty == true)
            ? Image.asset(
                errorImage!,
                fit: BoxFit.cover,
              )
            : FWAssets.emptyIcon,
      );
    }
  }

  if (radius == 0) {
    return childWidget();
  } else {
    return ClipWidget(
      radius: radius,
      bottomLeft: bottomLeft,
      bottomRight: bottomRight,
      child: childWidget(),
    );
  }
}

///ImageProvider加载方法
// ignore: non_constant_identifier_names
ImageProvider WebImageProvider(
  String? url, {
  WebCacheImageScale scale = WebCacheImageScale.big,
}) {
  String _url = _getUrlWithSplit(url, scale);
  return ExtendedNetworkImageProvider(
    _url,
    headers: _header,
    cache: true,
  );
}

//预加载网络图片
void preloadWebImageUrl({
  required List imageUrls,
  WebCacheImageScale scale = WebCacheImageScale.big,
}) {
  if (imageUrls.isNotEmpty) {
    for (var url in imageUrls) {
      String urlString = _getUrlWithSplit(url, scale);
      getNetworkImageData(urlString, useCache: true);
    }
  }
}

///根据状态字段获取各个状态的widget
Widget getExtendedImageState({
  required ExtendedImageState state,
  String? placeholderImage,
  Widget? placeholderWidget,
  String? errorImage,
  bool retry = false, //点击重试
  bool displayPlaceholder = true,
}) {
  switch (state.extendedImageLoadState) {
    case LoadState.loading:
      if (displayPlaceholder == false) {
        return Container();
      }
      return placeholderWidget ??
          Container(
            color: FWColorPicker.colorFFF5F5F5,
            child: (placeholderImage?.isNotEmpty == true)
                ? Image.asset(
                    placeholderImage!,
                    fit: BoxFit.cover,
                  )
                : null,
          );

    case LoadState.completed:
      return state.completedWidget;

    case LoadState.failed:
      //remove memory cached
      state.imageProvider.evict();
      if (displayPlaceholder == false) {
        return Container();
      }
      return retry
          ? GestureDetector(
              child: Stack(
                fit: StackFit.expand,
                children: <Widget>[
                  (errorImage?.isNotEmpty == true)
                      ? Image.asset(
                          errorImage!,
                          fit: BoxFit.cover,
                        )
                      : FWAssets.emptyIcon,
                  //Icon(Icons.error),
                  const Positioned(
                    left: 0.0,
                    right: 0.0,
                    top: 0.0,
                    bottom: 0.0,
                    child: Text(
                      '点击重新加载',
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        color: Color(0xFF666666),
                      ),
                    ),
                  )
                ],
              ),
              onTap: () {
                state.reLoadImage();
              },
            )
          : (errorImage?.isNotEmpty == true)
              ? Image.asset(
                  errorImage!,
                  fit: BoxFit.cover,
                )
              : FWAssets.emptyIcon;
  }
}

String _getUrlWithSplit(String? url, WebCacheImageScale scale) {
  String urlSplit = "";
  String urlString = url ?? "";
  if (urlString.contains(FWConfig.qnFlag) == false) {
    urlSplit = "";
  } else {
    urlSplit = _getUrlSplit(scale);
    if (urlString.contains(FWConfig.qnProcessFlag) == true) {
      if (urlString.contains(FWConfig.qnProcess) == true && urlSplit.isNotEmpty) {
        urlString = urlString.replaceAll(FWConfig.qnProcess, urlSplit);
      } else if (urlString.contains(FWConfig.qnProcess2) == true &&
          urlSplit.isNotEmpty) {
        urlSplit = _getUrlSplit(scale, imageMogr2: true);
        urlString = urlString.replaceAll(FWConfig.qnProcess2, urlSplit);
      }
      urlSplit = "";
    }
  }
  // if (_url.endsWith(".mp4") == true) {
  //   urlSplit = Config.QN_VIDEO_SNAPSHOT_SMALL;
  // }
  return urlString + urlSplit;
}

String _getUrlSplit(
  WebCacheImageScale scale, {
  bool imageMogr2 = false,
}) {
  if (imageMogr2 == false) {
    switch (scale) {
      case WebCacheImageScale.normal:
        break;
      case WebCacheImageScale.mini:
        return FWConfig.qnImageSizeMini;
      case WebCacheImageScale.small:
        return FWConfig.qnImageSizeSmall;
      case WebCacheImageScale.middle:
        return FWConfig.qnImageSizeMiddle;
      case WebCacheImageScale.big:
        return FWConfig.qnImageSizeBig;
      case WebCacheImageScale.origin:
        return "";
    }
    return "";
  } else {
    switch (scale) {
      case WebCacheImageScale.normal:
        break;
      case WebCacheImageScale.mini:
        return FWConfig.qnImageSizeMini2;
      case WebCacheImageScale.small:
        return FWConfig.qnImageSizeSmall2;
      case WebCacheImageScale.middle:
        return FWConfig.qnImageSizeMiddle2;
      case WebCacheImageScale.big:
        return FWConfig.qnImageSizeBig2;
      case WebCacheImageScale.origin:
        return "";
    }
    return "";
  }
}

